package cn.tp.ksoft.civil_driver.module.login;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import java.io.File;
import java.util.Calendar;

import cn.tp.ksoft.civil_driver.DriverBaseActivity;
import cn.tp.ksoft.civil_driver.R;
import cn.tp.ksoft.civil_driver.bean.BrandVo;
import cn.tp.ksoft.civil_driver.bean.CarType;
import cn.tp.ksoft.civil_driver.bean.DriverDto;
import cn.tp.ksoft.civil_driver.bean.EnterpriseDto;
import cn.tp.ksoft.civil_driver.bean.ResultBean;
import cn.tp.ksoft.civil_driver.dialog.CarColorDialog;
import cn.tp.ksoft.civil_driver.dialog.CarTypeDialog;
import cn.tp.ksoft.civil_driver.dialog.DialogCallBack;
import cn.tp.ksoft.civil_driver.dialog.DriveAgeDialog;
import cn.tp.ksoft.civil_driver.dialog.SeatDialog;
import cn.tp.ksoft.civil_driver.request.DriverRequest;
import cn.tp.ksoft.civil_driver.request.RequestModules;
import cn.tp.ksoft.civil_driver.utils.Constants;
import cn.tp.ksoft.civil_driver.utils.Utils;
import cn.tp.ksoft.civil_driver.view.simple.SimpleTextWatcher;

/**
 * Created by zhusong on 16/5/1.
 */
public class RegisterActivity extends DriverBaseActivity implements View.OnClickListener, Runnable, RequestModules{

    private DriverRequest request;
    private ViewAnimator mContentController;

    private final int INDEX_VALID_PHONE = 0;
    private final int INDEX_INPUT_INFO = 1;
    private final int INDEX_FINISH = 2;

    private final int REQUEST_VERIFY_CARDS = 1;
    private final int REQUEST_TAKE_PHOTO = 2;
    private final int REQUEST_CHOOSE_BRAND = 3;
    private final int REQUEST_CAR_OWNER = 4;
    private final int REQUEST_CAR_COLOR = 5;
    private final int REQUEST_CAR_TYPE = 6;
    private final int REQUEST_BRNAD_TYPE = 7;
    // head part
    private View mHead;
    private CheckBox mValidPhoneCb;
    private CheckBox mInputInfoCb;
    private CheckBox mFinishCb;
    private View mInputInfoLine;
    private View mFinishLine;
    private int lineNormalColor;
    private int lineCheckedColor;

    // valid phone part
    private EditText mPhoneEdt;
    private EditText mPwdEdt;
    private EditText mCodeEdt;
    private CheckBox mAgreeCb;
    private Button mGetCodeBtn;
    private Button mRegBtn;
    private int mLeaveTime = -1;

    // valid input info part
    private ImageView mIconIv;
    private EditText mNameEdt;
    private EditText mIdCardEdt;
    private EditText mCarNumEdt;
    private TextView mDriverAgeTv;
    private TextView mBrandTv;
    private TextView mBrandTypeTv;
    private TextView mCarTypeTv;
    private TextView mColorTv;
    private TextView mOwnerTv;
    private TextView mSeatTv;
    private File iconFile;
    private DriveAgeDialog mAgeDialog;
    private CarColorDialog mCarColorDialog;
    private CarTypeDialog mCarTypeDialog;
    private SeatDialog mSeatDailog;
    private boolean isReApply;

    private WeakHandler mHandler = new WeakHandler(this);

    private DriverDto driverDto = new DriverDto();
    private String validateCode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.driver_activity_register);
        if (null != getIntent()) {
            isReApply = getIntent().getBooleanExtra(Constants.KEY_ISREAPPLY, false);
        }
        mContentController = (ViewAnimator) findViewById(R.id.content_control);
        // head part
        mHead = findViewById(R.id.rl_head);
        mValidPhoneCb = (CheckBox) findViewById(R.id.cb_valid_phone);
        mInputInfoCb = (CheckBox) findViewById(R.id.cb_input_info);
        mFinishCb = (CheckBox) findViewById(R.id.cb_finish);
        mInputInfoLine = findViewById(R.id.line_input_info);
        mFinishLine = findViewById(R.id.line_finish);
        lineNormalColor = getResources().getColor(R.color.colorTextHint);
        lineCheckedColor = getResources().getColor(R.color.colorHotSpot);

        // valid phone part
        mPhoneEdt = (EditText) findViewById(R.id.edt_phone);
        mPhoneEdt.addTextChangedListener(new SimpleTextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    // validate
                    request.validatePhone(s.toString());
                }
            }
        });
        mPwdEdt = (EditText) findViewById(R.id.edt_pwd);
        mCodeEdt = (EditText) findViewById(R.id.edt_code);
        mBrandTv = (TextView) findViewById(R.id.tv_brand);
        mDriverAgeTv = (TextView) findViewById(R.id.tv_drive_age);
        mBrandTypeTv = (TextView) findViewById(R.id.tv_brand_type);
        mCarTypeTv = (TextView) findViewById(R.id.tv_car_type);
        mColorTv = (TextView) findViewById(R.id.tv_car_color);
        mOwnerTv = (TextView) findViewById(R.id.tv_car_owner);
        mSeatTv = (TextView) findViewById(R.id.tv_seat);
        mGetCodeBtn = (Button) findViewById(R.id.btn_get_code);
        mGetCodeBtn.setOnClickListener(this);
        mRegBtn = (Button) findViewById(R.id.btn_register_login);
        mRegBtn.setOnClickListener(this);
        mAgreeCb = (CheckBox) findViewById(R.id.cb_agree);

        // input info part
        findViewById(R.id.btn_finish).setOnClickListener(this);
        findViewById(R.id.ll_icon).setOnClickListener(this);
        mIconIv = (ImageView) findViewById(R.id.iv_icon);
        mNameEdt = (EditText) findViewById(R.id.edt_name);
        mIdCardEdt = (EditText) findViewById(R.id.edt_id_card);
        mCarNumEdt = (EditText) findViewById(R.id.edt_car_number);
        findViewById(R.id.ll_drive_age).setOnClickListener(this);
        findViewById(R.id.ll_brand).setOnClickListener(this);
        findViewById(R.id.ll_brand_type).setOnClickListener(this);
        findViewById(R.id.ll_car_color).setOnClickListener(this);
        findViewById(R.id.ll_car_owner).setOnClickListener(this);
        findViewById(R.id.ll_car_type).setOnClickListener(this);
        findViewById(R.id.ll_seat).setOnClickListener(this);
        // update
        if (isReApply) {
            mHead.setVisibility(View.GONE);
            updateTitle(getString(R.string.driver_login_reapply));
            mContentController.setDisplayedChild(INDEX_INPUT_INFO);
        } else {
            updateTitle(getString(R.string.driver_login_register));
        }

        request = new DriverRequest(this, mHandler);
    }

    @Override
    public void onBackPressed() {
        int index = mContentController.getDisplayedChild();
        if (isReApply || index <= INDEX_VALID_PHONE) {
            super.onBackPressed();
            return;
        }

        if (index > INDEX_VALID_PHONE) {
            mContentController.setInAnimation(this, R.anim.slide_in_from_l_to_r);
            mContentController.setOutAnimation(this, R.anim.slide_out_from_l_to_r);
            showContent(index - 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_VERIFY_CARDS) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        } else if (requestCode == REQUEST_TAKE_PHOTO) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                mIconIv.setImageURI(uri);
                String filePath = Utils.getImageAbsolutePath(this, uri);
                if (TextUtils.isEmpty(filePath) || !(iconFile = new File(filePath)).exists()) {
                    Toast.makeText(this, "图片未找到", Toast.LENGTH_SHORT).show();
                    return;
                }

                request.setPhoto(iconFile);
            }
        } else if (requestCode == REQUEST_CHOOSE_BRAND) {
            if (resultCode == RESULT_OK) {
                BrandVo brand = data.getParcelableExtra(Constants.KEY_BRAND);
                driverDto.setCarBrand(brand.getName());
                mBrandTv.setText(brand.getName());
                mBrandTv.setTag(brand);
                mBrandTypeTv.setText(null);
            }
        } else if (requestCode == REQUEST_CAR_OWNER) {
            if (resultCode == RESULT_OK) {
                EnterpriseDto enterprise = (EnterpriseDto) data.getSerializableExtra(Constants.KEY_RADIO_DATA);
                driverDto.setProviderId(enterprise.getId());
                mOwnerTv.setText(enterprise.getName());
            }
        } else if (requestCode == REQUEST_BRNAD_TYPE) {
            if (resultCode == RESULT_OK) {
                String brandType = data.getStringExtra(Constants.KEY_RADIO_DATA);
                driverDto.setCarBrandType(brandType);
                mBrandTypeTv.setText(brandType);
            }
        }
    }

    private void showContent(int contentIndex) {
        hideSoftInput();
        setHeadStatus(contentIndex);
        mContentController.setDisplayedChild(contentIndex);
    }

    private void setHeadStatus(int contentIndex) {
        if (contentIndex == INDEX_VALID_PHONE) {
            mValidPhoneCb.setChecked(true);
            mInputInfoCb.setChecked(false);
            mFinishCb.setChecked(false);
            mInputInfoLine.setBackgroundColor(lineNormalColor);
            mFinishLine.setBackgroundColor(lineNormalColor);
        } else if (contentIndex == INDEX_INPUT_INFO) {
            mInputInfoCb.setChecked(true);
            mFinishCb.setChecked(false);
            mValidPhoneCb.setChecked(true);
            mInputInfoLine.setBackgroundColor(lineCheckedColor);
            mFinishLine.setBackgroundColor(lineNormalColor);
        } else if (contentIndex == INDEX_FINISH) {
            mValidPhoneCb.setChecked(true);
            mInputInfoCb.setChecked(true);
            mFinishCb.setChecked(true);
            mInputInfoLine.setBackgroundColor(lineCheckedColor);
            mFinishLine.setBackgroundColor(lineCheckedColor);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_code : {
                String phone = mPhoneEdt.getText().toString();
                boolean isPhone = Utils.isPhone(phone);
                if (!isPhone) {
                    Toast.makeText(this, getString(R.string.driver_tip_input_correct_phone_number), Toast.LENGTH_SHORT).show();
                    return;
                }
                mLeaveTime = 60;
                request.getValidateCode(phone, RequestModules.OP_REGISTER);
                mHandler.post(this);
                mGetCodeBtn.setEnabled(false);
                break;
            }
            case R.id.btn_register_login: {
                String phone = mPhoneEdt.getText().toString();
                String pwd = mPwdEdt.getText().toString();
                String code = mCodeEdt.getText().toString();
                if (TextUtils.isEmpty(phone)
                        || TextUtils.isEmpty(pwd)
                        || TextUtils.isEmpty(code)) {
                    Toast.makeText(this, getString(R.string.driver_tip_input_phone_pwd_code),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (pwd.length() < 6) {
                    Toast.makeText(this, getString(R.string.driver_tip_pwd_min_len),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!mAgreeCb.isChecked()) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_agree_protocol),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                driverDto.setTelephone(phone);
                driverDto.setLoginPwd(pwd);
                validateCode = code;
                request.doRegister(driverDto, validateCode);
                break;
            }

            case R.id.btn_finish : {
                // check
                String name = mNameEdt.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(this, getString(R.string.driver_please_input_full_name),
                            Toast.LENGTH_SHORT).show();
                    mNameEdt.requestFocus();
                    return;
                }
                driverDto.setName(name);

                String idCard = mIdCardEdt.getText().toString();
                if (TextUtils.isEmpty(idCard)) {
                    Toast.makeText(this, getString(R.string.driver_please_input_id_card),
                            Toast.LENGTH_SHORT).show();
                    mIdCardEdt.requestFocus();
                    return;
                }
                driverDto.setIdcard(idCard);

                if (TextUtils.isEmpty(mDriverAgeTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_drive_age)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                String carNumber = mCarNumEdt.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(this, getString(R.string.driver_please_input_car_number),
                            Toast.LENGTH_SHORT).show();
                    mCarNumEdt.requestFocus();
                    return;
                }
                driverDto.setCarNo(carNumber);

                if (TextUtils.isEmpty(mBrandTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_brand)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mBrandTypeTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_brand_model)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mCarTypeTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_type)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mColorTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_color)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mSeatTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_seat)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mOwnerTv.getText())) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_owner)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                /*driverDto.setTelephone("15068822229");
                driverDto.setLoginPwd("123456");
                validateCode = "123456";

                driverDto.setName("朱凇");
                driverDto.setCarNo("沪C82Q59");
                driverDto.setDriveNo("XXXXXXX123456");
                driverDto.setCarBrand("马自达");
                driverDto.setCarBrandType("昂克赛拉");
                driverDto.setCarType(1);
                driverDto.setCarColor("红色");
                driverDto.setProviderId(1l);
                driverDto.setIdcard("330183199008230511");
                driverDto.setPassportTime(Calendar.getInstance().getTime());
                driverDto.setCarSeat(4);*/
                request.finishInfo(driverDto.getName(), driverDto.getIdcard(), driverDto.getPassportTime(),
                        driverDto.getCarNo(), driverDto.getCarBrand(), driverDto.getCarBrandType(),
                        driverDto.getCarColor(), driverDto.getCarSeat(), driverDto.getProviderId());
                break;
            }

            case R.id.ll_icon : {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                break;
            }

            case R.id.ll_brand : {
                Intent intent = new Intent(this, BrandActivity.class);
                startActivityForResult(intent, REQUEST_CHOOSE_BRAND);
                break;
            }
            case R.id.ll_brand_type : {
                BrandVo brand = (BrandVo) mBrandTv.getTag();
                if (brand == null) {
                    Toast.makeText(this, getString(R.string.driver_tip_please_select_xxx,
                            getString(R.string.driver_car_brand_model)),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(this, RadioItemSelectActivity.class);
                intent.putExtra(Constants.KEY_RADIO_TYPE, Constants.VALUE_RADIO_BRAND_TYPE);
                intent.putExtra(Constants.KEY_BRAND, brand);
                startActivityForResult(intent, REQUEST_BRNAD_TYPE);
                break;
            }

            case R.id.ll_drive_age : {
                if (null == mAgeDialog) {
                    mAgeDialog = new DriveAgeDialog(this);
                    mAgeDialog.setCallBack(new DialogCallBack() {
                        @Override
                        public void onPositiveClick(Object... result) {
                            int year = (Integer) result[0];
                            int month = (Integer) result[1];
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(year, month, 1);
                            mDriverAgeTv.setText(getString(R.string.driver_date_year_month, year, month));
                            driverDto.setPassportTime(calendar.getTime());
                        }

                        @Override
                        public void onNegativeClick(Object... result) {

                        }
                    });
                }
                mAgeDialog.show();
                break;
            }

            case R.id.ll_car_color : {
                if (null == mCarColorDialog) {
                    mCarColorDialog = new CarColorDialog(this);
                    mCarColorDialog.setCallBack(new DialogCallBack() {
                        @Override
                        public void onPositiveClick(Object... result) {
                            String color = (String) result[0];
                            driverDto.setCarColor(color);
                            mColorTv.setText(color);
                        }

                        @Override
                        public void onNegativeClick(Object... result) {

                        }
                    });
                }
                mCarColorDialog.show();
                break;
            }

            case R.id.ll_car_owner : {
                Intent intent = new Intent(this, RadioItemSelectActivity.class);
                intent.putExtra(Constants.KEY_RADIO_TYPE, Constants.VALUE_RADIO_OWNER);
                startActivityForResult(intent, REQUEST_CAR_OWNER);

                break;
            }

            case R.id.ll_car_type : {
                if (null == mCarTypeDialog) {
                    mCarTypeDialog = new CarTypeDialog(this);
                    mCarTypeDialog.setCallBack(new DialogCallBack() {
                        @Override
                        public void onPositiveClick(Object... result) {
                            CarType carType = (CarType) result[0];
                            driverDto.setCarType(carType.getTypeId());
                            mCarTypeTv.setText(carType.getTypeName());
                        }

                        @Override
                        public void onNegativeClick(Object... result) {

                        }
                    });
                }
                mCarTypeDialog.show();

                break;
            }

            case R.id.ll_seat : {
                if (null == mSeatDailog) {
                    mSeatDailog = new SeatDialog(this);
                    mSeatDailog.setCallBack(new DialogCallBack() {
                        @Override
                        public void onPositiveClick(Object... result) {
                            Integer seat = (Integer) result[0];
                            driverDto.setCarSeat(seat);
                            mSeatTv.setText(String.valueOf(seat));
                        }

                        @Override
                        public void onNegativeClick(Object... result) {

                        }
                    });
                }
                mSeatDailog.show();
                break;
            }
        }
    }

    @Override
    public void run() {
        mLeaveTime--;
        if (mLeaveTime > 0) {
            String text = getString(R.string.driver_get_code_time, mLeaveTime);
            mGetCodeBtn.setText(text);
            mHandler.postDelayed(this, 1000);
        } else {
            String text = getString(R.string.driver_get_code);
            mGetCodeBtn.setText(text);
            mGetCodeBtn.setEnabled(true);
        }
    }

    @Override
    protected void handleSuccessResult(int what, @NonNull ResultBean result) {
        switch (what) {
            case VALIDATEPHONE : {
                mRegBtn.setEnabled(result.isSuccess());
                break;
            }
            case GETVALIDATECODE : {
                Toast.makeText(this, getString(R.string.driver_tip_verify_code_sended),
                        Toast.LENGTH_SHORT).show();
                break;
            }

            case DOREGISTER : {
                // finishInfo
                mContentController.setInAnimation(this, R.anim.slide_in_from_r_to_l);
                mContentController.setOutAnimation(this, R.anim.slide_out_from_r_to_l);
                showContent(INDEX_INPUT_INFO);
                break;
            }

            case SETPHOTO : {
                break;
            }
            case FINISHINFO : {
                Intent intent = new Intent(this, VerifyCardsActivity.class);
                startActivityForResult(intent, REQUEST_VERIFY_CARDS);
                break;
            }
        }
    }
}
